/**
 * 手写connect函数
 *   参数一  函数
 *   参数二  函数
 *   返回值  函数 => 高阶组件
 */

import React from 'react'
import { StoreContext } from './storeContext'

export const connect = (mapStateToProps, mapDispatchToProps) => {
  return (WrappedComponent) => {
    class NewComponent extends React.Component {
      constructor(props) {
        super(props)
        this.subscribe = null
      }
      componentDidMount() {
        console.log('我更新了')
        this.context.subscribe(() => {
          this.setState(mapStateToProps(this.context.getState()))
        })
      }
      componentWillUnmount() {
        this.subscribe = null
      }
      render() {
        const state = mapStateToProps(this.context.getState())
        const action = mapDispatchToProps(this.context.dispatch)
        console.log('我变化了')
        return <WrappedComponent { ...this.props } { ...state } { ...action }></WrappedComponent>
      }
    }
    NewComponent.contextType = StoreContext
    // 返回的那个组件
    return NewComponent
  }
}